package cc.customer.web.sys.controller.system;

import cc.customer.common.annotation.Log;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.utils.FileUtils;
import cc.customer.system.domain.MyUser;
import cc.customer.system.service.UserService;
import cc.customer.web.sys.controller.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class UserController extends BaseController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**u用户的首页面**/
    @RequestMapping("user")
    public String index(Model model) {
        return "system/user/user_index";
    }
    /**用户的新增弹框**/
    @RequestMapping("user/addDialog")
    public String userAddDialog(){
        return "system/user/user_add";
    }
    /**用户的编辑模块**/
    @RequestMapping("user/updateDialog")
    public String userUpdateDialog(){return "system/user/user_edit";}
    /**用户首页修改**/
    @RequestMapping("user/profile")
    public String userupDateMyInfo(Model model){
        MyUser user = super.getCurrentUser();
        user = this.userService.findUserProfile(user);
        String ssex = user.getSsex();
        if (MyUser.SEX_MALE.equals(ssex)) {
            user.setSsex("男");
        } else if (MyUser.SEX_FEMALE.equals(ssex)) {
            user.setSsex("女");
        } else {
            user.setSsex("保密");
        }
        model.addAttribute("user", user);
        return "system/user/user_profile";
    }
    /**更换用户头像**/
    @RequestMapping("user/moAvatar")
    public String changeAvatar(){return "system/user/avatar";}
    /**修改密码**/
    @RequestMapping("user/moPassword")
    public  String changePassword(){return "system/user/password";}

    /**验证账户**/
    @RequestMapping("user/checkUserName")
    @ResponseBody
    public boolean checkUserName(String username) {
        MyUser result = this.userService.findByName(username);
        return result == null;
    }
    /**根据usereId获取用户**/
    @RequestMapping("user/getUser")
    @ResponseBody
    public ResponseBo getUser(Long userId) {
        try {
            MyUser user = this.userService.findById(userId);
            return ResponseBo.ok(user);
        } catch (Exception e) {
            log.error("获取用户失败", e);
            return ResponseBo.error("获取用户失败，请联系网站管理员！");
        }
    }

    @RequestMapping("user/list")
    @ResponseBody
    public Map<String, Object> userList(QueryRequest request, MyUser user) {
        return super.selectByPageNumSize(request, () -> this.userService.findUserWithDeptAllUser(user));
    }

    @RequestMapping("user/add")
    @ResponseBody
    public ResponseBo addUser(MyUser user, Long[] roles) {
        try {
            user.setPassword(this.passwordEncoder.encode(user.getPassword()));
            user.setStatus("1");
            this.userService.addUser(user, roles);
            return ResponseBo.ok("新增用户成功！");
        } catch (Exception e) {
            log.error("新增用户失败", e);
            return ResponseBo.error("新增用户失败，请联系网站管理员！");
        }
    }

    @RequestMapping("user/update")
    @ResponseBody
    public ResponseBo updateUser(MyUser user, Long[] rolesSelect) {
        try {
            user.setStatus("1");
            System.out.println(user.getDeptId());
            this.userService.updateUser(user, rolesSelect);
            return ResponseBo.ok("修改用户成功！");
        } catch (Exception e) {
            log.error("修改用户失败", e);
            return ResponseBo.error("修改用户失败，请联系网站管理员！");
        }
    }

    @RequestMapping("user/delete")
    @ResponseBody
    public ResponseBo deleteUsers(String ids) {
        try {
            this.userService.batchUpdateUser(ids);
            return ResponseBo.ok("删除用户成功！");
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return ResponseBo.error("删除用户失败，请联系网站管理员！");
        }
    }
    /**检查原密码是否正确*/
    @RequestMapping("user/checkPassword")
    @ResponseBody
    public boolean checkPassword(String password,String username) {
        return this.passwordEncoder.matches(password, username);
    }
    /**修改密码**/
    @RequestMapping("user/updatePassword")
    @ResponseBody
    public ResponseBo updatePassword(String newPassword,String username) {
        try {
            this.userService.updatePassword(this.passwordEncoder.encode(newPassword), username);
            return ResponseBo.ok("更改密码成功");
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return ResponseBo.error("更改密码失败，请联系网站管理员！");
        }
    }
    /**获取用户信息**/
    @RequestMapping("user/getUserProfile")
    @ResponseBody
    public ResponseBo getUserProfile(Long userId) {
        try {
            MyUser user = new MyUser();
            user.setUserId(userId);
            return ResponseBo.ok(this.userService.findUserProfile(user));
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return ResponseBo.error("获取用户信息失败，请联系网站管理员！");
        }
    }
    @RequestMapping("user/updateUserProfile")
    @ResponseBody
    public ResponseBo updateUserProfile(MyUser user) {
        try {
            this.userService.updateUserProfile(user);
            return ResponseBo.ok("更新个人信息成功！");
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return ResponseBo.error("更新用户信息失败，请联系网站管理员！");
        }
    }

    @RequestMapping("user/changeAvatar")
    @ResponseBody
    public ResponseBo changeAvatar(String imgName) {
        try {
            String[] img = imgName.split("/");
            String realImgName = img[img.length - 1];
            MyUser user = getCurrentUser();
            user.setAvatar(realImgName);
            this.userService.updateNotNull(user);
            return ResponseBo.ok("更新头像成功！");
        } catch (Exception e) {
            log.error("更换头像失败", e);
            return ResponseBo.error("更新头像失败，请联系网站管理员！");
        }
    }


    @RequestMapping("user/excel")
    @ResponseBody
    public ResponseBo userExcel(MyUser user) {
        try {
            List<MyUser> list = this.userService.findUserWithDept(user);
            return FileUtils.createExcelByPOIKit("用户表", list, MyUser.class);
        } catch (Exception e) {
            log.error("导出用户信息Excel失败", e);
            return ResponseBo.error("导出Excel失败，请联系网站管理员！");
        }
    }

    /**根据人名查人员**/
    @RequestMapping("user/selectUserList")
    @ResponseBody
    public List<MyUser> selectUserList(MyUser user){
        try{
            return userService.selectUserByName(user);
        }catch (Exception e){
            log.error("获取用户失败:"+e.getMessage());
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    /**根据部门查人员**/
    @RequestMapping("user/selectUserByDept")
    @ResponseBody
    public List<MyUser> selectUserByDept(MyUser user){
        try{
            List<MyUser> list = userService.selectUserByDeptid(user);
            return list;
        }catch (Exception e){
            log.error("获取用户失败:"+e.getMessage());
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
